import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useLayerStore = defineStore('layer', () => {
  // 图层数据
  const layers = ref([
    {
      id: 'background',
      name: '背景层',
      type: 'background',
      visible: true,
      locked: false,
      opacity: 1,
      color: '#ffffff',
      order: 0,
      objects: []
    },
    {
      id: 'grid',
      name: '网格层',
      type: 'grid',
      visible: true,
      locked: true,
      opacity: 1,
      color: '#e5e7eb',
      order: 1,
      objects: []
    },
    {
      id: 'walls',
      name: '墙体层',
      type: 'walls',
      visible: true,
      locked: false,
      opacity: 1,
      color: '#374151',
      order: 2,
      objects: []
    },
    {
      id: 'furniture',
      name: '家具层',
      type: 'furniture',
      visible: true,
      locked: false,
      opacity: 1,
      color: '#3B82F6',
      order: 3,
      objects: [
        {
          id: 'furniture-1',
          type: 'table',
          name: '桌子',
          x: 100,
          y: 100,
          width: 80,
          height: 60,
          color: '#8B4513',
          rotation: 0,
          zIndex: 1,
          layerId: 'furniture'
        },
        {
          id: 'furniture-2',
          type: 'chair',
          name: '椅子',
          x: 200,
          y: 150,
          width: 40,
          height: 50,
          color: '#654321',
          rotation: 0,
          zIndex: 2,
          layerId: 'furniture'
        }
      ]
    },
    {
      id: 'doors',
      name: '门窗层',
      type: 'doors',
      visible: true,
      locked: false,
      opacity: 1,
      color: '#8B4513',
      order: 4,
      objects: []
    },
    {
      id: 'circuits',
      name: '电路层',
      type: 'circuits',
      visible: true,
      locked: false,
      opacity: 1,
      color: '#FFD700',
      order: 5,
      objects: []
    },
    {
      id: 'annotations',
      name: '标注层',
      type: 'annotations',
      visible: true,
      locked: false,
      opacity: 1,
      color: '#FF6B6B',
      order: 6,
      objects: []
    },
    {
      id: 'measurements',
      name: '测量层',
      type: 'measurements',
      visible: false,
      locked: false,
      opacity: 1,
      color: '#10B981',
      order: 7,
      objects: []
    }
  ])

  // 当前活动图层
  const activeLayerId = ref('furniture')

  // 计算属性
  const visibleLayers = computed(() => 
    layers.value.filter(layer => layer.visible)
  )

  const unlockedLayers = computed(() => 
    layers.value.filter(layer => !layer.locked)
  )

  const activeLayer = computed(() => 
    layers.value.find(layer => layer.id === activeLayerId.value)
  )

  const layerCount = computed(() => layers.value.length)

  const objectCount = computed(() => 
    layers.value.reduce((total, layer) => total + layer.objects.length, 0)
  )

  const sortedLayers = computed(() => 
    [...layers.value].sort((a, b) => a.order - b.order)
  )

  // Actions
  const createLayer = (layerData) => {
    const newLayer = {
      id: generateId(),
      name: '新图层',
      type: 'custom',
      visible: true,
      locked: false,
      opacity: 1,
      color: '#6B7280',
      order: layers.value.length,
      objects: [],
      ...layerData
    }
    
    layers.value.push(newLayer)
    return newLayer
  }

  const deleteLayer = (layerId) => {
    const index = layers.value.findIndex(layer => layer.id === layerId)
    if (index !== -1 && layers.value[index].type !== 'background') {
      // 将图层中的对象移动到默认图层
      const objects = layers.value[index].objects
      if (objects.length > 0) {
        moveObjectsToLayer(objects.map(obj => obj.id), 'furniture')
      }
      
      layers.value.splice(index, 1)
      
      // 如果删除的是当前活动图层，切换到家具层
      if (activeLayerId.value === layerId) {
        setActiveLayer('furniture')
      }
    }
  }

  const duplicateLayer = (layerId) => {
    const layer = layers.value.find(l => l.id === layerId)
    if (layer) {
      const duplicatedLayer = {
        ...layer,
        id: generateId(),
        name: `${layer.name} 副本`,
        objects: [] // 不复制对象
      }
      
      layers.value.push(duplicatedLayer)
      return duplicatedLayer
    }
  }

  const setActiveLayer = (layerId) => {
    const layer = layers.value.find(l => l.id === layerId)
    if (layer && !layer.locked) {
      activeLayerId.value = layerId
    }
  }

  const toggleLayerVisibility = (layerId) => {
    const layer = layers.value.find(l => l.id === layerId)
    if (layer) {
      layer.visible = !layer.visible
    }
  }

  const toggleLayerLock = (layerId) => {
    const layer = layers.value.find(l => l.id === layerId)
    if (layer) {
      layer.locked = !layer.locked
      
      // 如果锁定的是当前活动图层，切换到其他未锁定的图层
      if (layer.locked && activeLayerId.value === layerId) {
        const unlockedLayer = layers.value.find(l => !l.locked && l.id !== layerId)
        if (unlockedLayer) {
          setActiveLayer(unlockedLayer.id)
        }
      }
    }
  }

  const setLayerOpacity = (layerId, opacity) => {
    const layer = layers.value.find(l => l.id === layerId)
    if (layer) {
      layer.opacity = Math.max(0, Math.min(1, opacity))
    }
  }

  const setLayerColor = (layerId, color) => {
    const layer = layers.value.find(l => l.id === layerId)
    if (layer) {
      layer.color = color
    }
  }

  const renameLayer = (layerId, name) => {
    const layer = layers.value.find(l => l.id === layerId)
    if (layer && name.trim()) {
      layer.name = name.trim()
    }
  }

  const moveLayer = (layerId, newOrder) => {
    const layer = layers.value.find(l => l.id === layerId)
    if (layer) {
      const oldOrder = layer.order
      layer.order = newOrder
      
      // 重新排序其他图层
      layers.value.forEach(l => {
        if (l.id !== layerId) {
          if (oldOrder < newOrder && l.order > oldOrder && l.order <= newOrder) {
            l.order--
          } else if (oldOrder > newOrder && l.order < oldOrder && l.order >= newOrder) {
            l.order++
          }
        }
      })
    }
  }

  const addObjectToLayer = (layerId, object) => {
    const layer = layers.value.find(l => l.id === layerId)
    if (layer) {
      layer.objects.push(object)
    }
  }

  const removeObjectFromLayer = (layerId, objectId) => {
    const layer = layers.value.find(l => l.id === layerId)
    if (layer) {
      const index = layer.objects.findIndex(obj => obj.id === objectId)
      if (index !== -1) {
        layer.objects.splice(index, 1)
      }
    }
  }

  const moveObjectToLayer = (objectId, targetLayerId) => {
    // 从所有图层中查找对象
    let sourceLayer = null
    let object = null
    
    for (const layer of layers.value) {
      const objIndex = layer.objects.findIndex(obj => obj.id === objectId)
      if (objIndex !== -1) {
        sourceLayer = layer
        object = layer.objects[objIndex]
        layer.objects.splice(objIndex, 1)
        break
      }
    }
    
    // 添加到目标图层
    if (object) {
      addObjectToLayer(targetLayerId, object)
    }
  }

  const moveObjectsToLayer = (objectIds, targetLayerId) => {
    objectIds.forEach(objectId => {
      moveObjectToLayer(objectId, targetLayerId)
    })
  }

  const getLayerById = (layerId) => {
    return layers.value.find(l => l.id === layerId)
  }

  const getLayerByType = (type) => {
    return layers.value.find(l => l.type === type)
  }

  const getObjectsInLayer = (layerId) => {
    const layer = layers.value.find(l => l.id === layerId)
    return layer ? layer.objects : []
  }

  const getAllObjects = () => {
    return layers.value.flatMap(layer => layer.objects)
  }

  const getVisibleObjects = () => {
    return layers.value
      .filter(layer => layer.visible)
      .flatMap(layer => layer.objects)
  }

  const getObjectsByType = (type) => {
    return getAllObjects().filter(obj => obj.type === type)
  }

  const findObjectLayer = (objectId) => {
    for (const layer of layers.value) {
      if (layer.objects.find(obj => obj.id === objectId)) {
        return layer
      }
    }
    return null
  }

  const showAllLayers = () => {
    layers.value.forEach(layer => {
      layer.visible = true
    })
  }

  const hideAllLayers = () => {
    layers.value.forEach(layer => {
      if (layer.type !== 'background') {
        layer.visible = false
      }
    })
  }

  const lockAllLayers = () => {
    layers.value.forEach(layer => {
      layer.locked = true
    })
  }

  const unlockAllLayers = () => {
    layers.value.forEach(layer => {
      layer.locked = false
    })
  }

  const mergeLayers = (layerIds, targetLayerId) => {
    const targetLayer = layers.value.find(l => l.id === targetLayerId)
    if (!targetLayer) return
    
    layerIds.forEach(layerId => {
      if (layerId !== targetLayerId) {
        const layer = layers.value.find(l => l.id === layerId)
        if (layer) {
          // 移动所有对象到目标图层
          layer.objects.forEach(obj => {
            targetLayer.objects.push(obj)
          })
          
          // 删除原图层
          deleteLayer(layerId)
        }
      }
    })
  }

  const exportLayers = () => {
    return {
      layers: layers.value,
      activeLayerId: activeLayerId.value,
      exportTime: Date.now()
    }
  }

  const importLayers = (data) => {
    if (data.layers && Array.isArray(data.layers)) {
      layers.value = data.layers
      activeLayerId.value = data.activeLayerId || 'furniture'
    }
  }

  const resetLayers = () => {
    layers.value = [
      {
        id: 'background',
        name: '背景层',
        type: 'background',
        visible: true,
        locked: false,
        opacity: 1,
        color: '#ffffff',
        order: 0,
        objects: []
      },
      {
        id: 'grid',
        name: '网格层',
        type: 'grid',
        visible: true,
        locked: true,
        opacity: 1,
        color: '#e5e7eb',
        order: 1,
        objects: []
      },
      {
        id: 'walls',
        name: '墙体层',
        type: 'walls',
        visible: true,
        locked: false,
        opacity: 1,
        color: '#374151',
        order: 2,
        objects: []
      },
      {
        id: 'furniture',
        name: '家具层',
        type: 'furniture',
        visible: true,
        locked: false,
        opacity: 1,
        color: '#3B82F6',
        order: 3,
        objects: []
      },
      {
        id: 'doors',
        name: '门窗层',
        type: 'doors',
        visible: true,
        locked: false,
        opacity: 1,
        color: '#8B4513',
        order: 4,
        objects: []
      },
      {
        id: 'circuits',
        name: '电路层',
        type: 'circuits',
        visible: true,
        locked: false,
        opacity: 1,
        color: '#FFD700',
        order: 5,
        objects: []
      },
      {
        id: 'annotations',
        name: '标注层',
        type: 'annotations',
        visible: true,
        locked: false,
        opacity: 1,
        color: '#FF6B6B',
        order: 6,
        objects: []
      },
      {
        id: 'measurements',
        name: '测量层',
        type: 'measurements',
        visible: false,
        locked: false,
        opacity: 1,
        color: '#10B981',
        order: 7,
        objects: []
      }
    ]
    
    activeLayerId.value = 'furniture'
  }

  // 辅助函数
  const generateId = () => {
    return Date.now().toString(36) + Math.random().toString(36).substr(2)
  }

  return {
    // 状态
    layers,
    activeLayerId,
    
    // 计算属性
    visibleLayers,
    unlockedLayers,
    activeLayer,
    layerCount,
    objectCount,
    sortedLayers,
    
    // Actions
    createLayer,
    deleteLayer,
    duplicateLayer,
    setActiveLayer,
    toggleLayerVisibility,
    toggleLayerLock,
    setLayerOpacity,
    setLayerColor,
    renameLayer,
    moveLayer,
    addObjectToLayer,
    removeObjectFromLayer,
    moveObjectToLayer,
    moveObjectsToLayer,
    getLayerById,
    getLayerByType,
    getObjectsInLayer,
    getAllObjects,
    getVisibleObjects,
    getObjectsByType,
    findObjectLayer,
    showAllLayers,
    hideAllLayers,
    lockAllLayers,
    unlockAllLayers,
    mergeLayers,
    exportLayers,
    importLayers,
    resetLayers
  }
})
